#!/usr/bin/python
# _*_ coding:utf-8 _*_

import cv2
import sys
import time
from six.moves import input

if sys.version_info.major != 3:
    print('请使用Python3')
    exit(1)

try:
    from common import screenshot
    from common.auto_adb import auto_adb
except Exception as ex:
    print(ex)
    print('请将脚本放在项目根目录中运行')
    print('请检查项目根目录中的 common 文件夹是否存在')
    exit(1)

adb = auto_adb()
adb.test_device()

VERSION = "0.0.1"
# 缩放比例
scale = 1
# 缩放比例
hand_area_min_width = 900 * scale
hand_area_max_width = 1080 * scale
# 缩放比例
star_area_min_height = 333 * scale
star_area_max_height = 1155 * scale

# 处理列表页
hand_tmp = cv2.imread('./resource/image/hand.png')
hand_tmp = cv2.resize(hand_tmp, (0, 0), fx=scale, fy=scale)
hand_tmp_width = hand_tmp.shape[0]
hand_tmp_height = hand_tmp.shape[1]

# 处理详情页
star_tmp = cv2.imread('./resource/image/star.png')
star_tmp = cv2.resize(star_tmp, (0, 0), fx=scale, fy=scale)
star_tmp_width = star_tmp.shape[0]
star_tmp_height = star_tmp.shape[1]


# 搜索 img 图片中 template 的位置，返回图片的左上角坐标
def search_touch_point(img, template):
    img = cv2.resize(img, (0, 0), fx=scale, fy=scale)
    result = cv2.matchTemplate(img, template, cv2.TM_SQDIFF)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    print('search_touch_point:x = {} y = {}'.format(min_loc[0], min_loc[1]))
    return min_loc[0], min_loc[1]


def search(file_path, template):
    img = cv2.imread(file_path)
    return search_touch_point(img, template)


def hand_search(img):
    touch_x, touch_y = search_touch_point(img, hand_tmp)
    if touch_x > hand_area_max_width:
        return 0, 0
    if touch_x < hand_area_min_width:
        return 0, 0
    return touch_x, touch_y + hand_tmp_height


def star_search(img):
    touch_x, touch_y = search_touch_point(img, star_tmp)
    if touch_y > star_area_max_height:
        return 0, 0
    if touch_y < star_area_min_height:
        return 0, 0
    return touch_x + star_tmp_width / 2, touch_y


# 模拟点击屏幕
def phone_touch(touch_x, touch_y):
    cmd = 'shell input tap {0} {1} '.format(touch_x, touch_y)
    print(cmd)
    adb.run(cmd)


# 模拟点击返回
def phone_back():
    cmd = 'shell input keyevent 4'
    print(cmd)
    adb.run(cmd)


def yes_or_no():
    """
    检查是否已经为启动程序做好了准备
    """
    while True:
        yes_or_no = str(input('请确保手机打开了 ADB 并连接了电脑，'
                              '然后打开跳一跳并【开始游戏】后再用本程序，确定开始？[y/n]:'))
        if yes_or_no == 'y':
            break
        elif yes_or_no == 'n':
            print('谢谢使用', end='')
            exit(0)
        else:
            print('请重新输入')


def main():
    """
    主函数
    """
    print('程序版本号：{}'.format(VERSION))
    print('激活窗口并按 CONTROL + C 组合键退出')
    screenshot.check_screenshot()
    print('check_screenshot end')
    while 1:
        img = screenshot.pull_screenshot()
        touch_x, touch_y = hand_search(img)
        print('定位：x = {} y = {}'.format(touch_x, touch_y))
        if touch_x > 0 and touch_y > 0:
            phone_touch(touch_x, touch_y)
            print('hand 程序将在 1秒 后继续')
            time.sleep(0.1)
            while 1:
                img = screenshot.pull_screenshot()
                touch_x, touch_y = star_search(img)
                print('定位：x = {} y = {}'.format(touch_x, touch_y))
                if touch_x > 0 and touch_y > 0:
                    phone_touch(touch_x, touch_y)
                    print('star 程序继续运行中')
                else:
                    phone_back()
                    break
            # 盲点
            # xx = 120
            # x = xx
            # y = 460
            # while 1:
            #     print('touch：x = {} y = {}'.format(x, y))
            #     phone_touch(x, y)
            #     x += xx
            #     if x >= 1080:
            #         y += xx
            #         x = xx
            #     if y >= 1160:
            #         phone_back()
            #         break
        else:
            print('hand 程序将在 2秒 后继续')
            time.sleep(2)


if __name__ == '__main__':
    try:
        yes_or_no()
        main()
        # img = cv2.imread('./temp/191252.png')
        # print(star_search(img))
    except KeyboardInterrupt:
        adb.run('kill-server')
        print('\n谢谢使用', end='')
        exit(0)
